import axios from 'axios'
import {useUserStore} from "@/stores/userStore";
import { ElMessage } from "element-plus";
const http = axios.create({
    baseURL:import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
})

http.interceptors.request.use(config=>{
    // 获取useUserStore实例
    const useStore = useUserStore()
    // 如果useStore实例有token属性，则将token属性添加到config.headers中
    if (useStore.token){
        config.headers.token = useStore.token
    }
    // 返回config
    return config
})
// 添加响应拦截器
http.interceptors.response.use((response) => {
    return response.data
}, (error) => {
    // 失败的回调
    let message = ''
    let status = error.response.status
    switch (status) {
        case 401:
            message = 'token过期'
            break
        case 403:
            message = '拒绝访问'
            break
        case 404:
            message = '请求地址不存在'
            break
        case 500:
            message = '服务器内部错误'
            break
        case 501:
            message = '服务未实现'
            break
        case 502:
            message = '网关错误'
            break
    }
    // 错误信息提示
    ElMessage({
        type: 'error',
        message
    })
    return Promise.reject(error)
})
export default http
//请求拦截器
